<?php

namespace app\index\service;

use common\helper\ArrayHelper;
use app\index\model\Half as HalfModel;

;

class Half
{

    /**
     * 添加或保存
     * @return type
     */
    public static function half_save($user_id,$date)
    {
        if (!empty(input('half_id')))
        {
            $HalfModel = HalfModel::where('id', input('half_id'))
                    ->where('member_id', $user_id)
                    ->find();
        }
        else
        {
            $HalfModel = new HalfModel();
        }
        $HalfModel->content = input('content', '模糊');
        $HalfModel->content = empty($HalfModel->content) ? '模糊' : $HalfModel->content;
        $start_time = strstr(input('time', ''), '-', true);
        $HalfModel->start_time = strtotime($date." ".$start_time);
        $HalfModel->type = input('type', '');
        $HalfModel->save();
        return json([ 'code' => 1, 'id' => $HalfModel->id ]);
    }

    /**
     * 获取挑战列表
     * @param type $state
     * @param type $user_id
     * @return type
     */
    public static function getHalfList($user_info, $type_map_color,$date)
    {
        $user_info['wake_up_time'] = str_replace('.', ':', $user_info['wake_up_time']);
        $user_info['sleep_time'] = str_replace('.', ':', $user_info['sleep_time']);
        $start_time = strtotime("{$date} {$user_info['wake_up_time']}:00");
        $end_time = strtotime("{$date} {$user_info['sleep_time']}:00");
        $half_list = HalfModel::whereTime('start_time', 'between', [ $start_time, $end_time ])
                ->select()
                ->toArray();
        foreach ($half_list as $key => $value)
        {
            unset($half_list[$key]);
            $name = to_date($value['start_time'], "H:i");
            $half_list[$name] = $value;
            $half_list[$name]['time'] = $name;
            $half_list[$name]['color'] = empty($type_map_color[$value['type']]) ? 'white' : $type_map_color[$value['type']];
        }
        $time_list = [];
        while ($end_time > $start_time)
        {
            $temp = to_date($start_time, "H:i");
            $start_time = strtotime("+30 minutes", $start_time);
            $name = $temp . '-' . to_date($start_time, "H:i");
            $time_list[$name] = empty($half_list[$temp]) ? [] : $half_list[$temp];
        }
        return $time_list;
    }

    /**
     * 统计月内每天的情况
     * @param type $where
     * @param type $date_arr
     * @return type
     */
    public static function month_stats($where, $date_arr)
    {
        $res = self::unitDaily($where, $date_arr);
        $return = [];
        foreach ($res as $key => $value)
        {
            $name = to_date($key, 'j日');
            $return[$name] = empty($return[$name]) ? $value : $return[$name] + $value;
        }
        return $return;
    }
    
    /**
     * 统计周内每天的情况
     * @param type $where
     * @param type $date_arr
     * @return type
     */
    public static function week_stats($where, $date_arr)
    {
        $res = self::unitDaily($where, $date_arr);
        $return = [];
        foreach ($res as $key => $value)
        {
            $name = to_date($key, 'j日');
            $return[$name] = empty($return[$name]) ? $value : $return[$name] + $value;
        }
        return $return;
    }

    /**
     * 统计某时间段内每天的情况
     * @param type $where
     * @param type $date_arr
     * @return type
     */
    public static function unitDaily($where, $date_arr)
    {
        list($start_date, $end_date) = $date_arr;
        //    时间字段
        $time_column = "start_time";
        $start_timestamp = to_time($start_date);
        $end_timestamp = to_time($end_date);
        $field = [
            'count(id)' => 'count',
            "from_unixtime({$time_column}, '%Y-%c-%e' )" => 'date',
        ];
        $res = HalfModel::whereTime($time_column, 'between', [ $start_date, $end_date ])
                ->where($where)
                ->group("from_unixtime($time_column,  '%Y-%c-%e' )")
                ->field($field)
                ->select()
                ->toArray();
        $res = array_column($res, 'count', 'date');
        $temp_timestamp = $start_timestamp;
        $dailyCount = [];
        while ($temp_timestamp <= $end_timestamp)
        {
            $temp_date = to_date($temp_timestamp, "Y-n-j");
            $temp = empty($res[$temp_date]) ? 0 : $res[$temp_date];
            $dailyCount[$temp_date] = empty($dailyCount[$temp_date]) ? $temp : $dailyCount[$temp_date] + $temp;
            $temp_timestamp += 86400;
        }
        return $dailyCount;
    }

    /**
     * 统计某时间段内每个月的情况
     * @param array $where
     * @param type $date_arr
     * @return type
     */
    public static function unitMonth($where = [], $date_arr)
    {
        list($start_date, $end_date) = $date_arr;
//    时间字段
        $time_column = "start_time";
//    时间字段转换日期需要什么函数,可选 date_format,from_unixtime
        $time_format = "from_unixtime";
        if (empty($year))
        {
            $year = to_date('Y');
        }
        $time_arr = [
            to_time($start_date),
            to_time($end_date),
        ];
        $result = HalfModel::where($where)
                ->whereTime($time_column, 'between', $time_arr)
                ->group('temp_month')
                ->field("$time_format($time_column,'%c') as temp_month,count(*) as value")
                ->select();
        $result = array_column($result->toArray(), 'value', 'temp_month');
        $month_list = [];
        $start_month = to_date($start_date, 'n');
        $end_month = to_date($end_date, 'n');
        for ($i = $start_month; $i <= $end_month; $i++)
        {
            $index = $i;
            if (!empty($result[$index]))
            {
                $temp = $result[$index];
                $month_list[$i . "月"] = money_float($temp);
            }
            else
            {
                $month_list[$i . "月"] = 0;
            }
        }
        return $month_list ?: [];
    }

    /**
     * 统计某段时间内类型情况
     * @param array $user_id
     * @param type $date_arr
     * @param type $type_map_name
     * @return type
     */
    public static function typeStats($user_id, $date_arr, $type_map_name)
    {
        $type_stats = HalfModel::where('member_id', $user_id)
                ->whereTime('start_time', 'between', $date_arr)
                ->group('type')
                ->column([ 'type', 'count(*) as count' ]);
        $template = array_fill_keys(array_keys($type_map_name), 0);
        $type_stats = ArrayHelper::array_merge_plus($template, $type_stats);
        $type_stats = ArrayHelper::array_keys_replace($type_stats, $type_map_name);
        return $type_stats;
    }

}
